package List;

import java.util.ArrayList;

/**
 * @author chenhong
 * @version 1.0
 * @description TODO
 * @date 2023/3/20 16:49
 */
public class MergeKSortedLists {
    public static void main(String[] args) {
        int a = 2;
        int b = 6;
        System.out.println(a + (b - a) >> 1);
    }

    public ListNode mergeKLists(ArrayList<ListNode> lists) {
        int len = lists.size();
        if (len == 0)
            return null;
        if (len == 1)
            return lists.get(0);
        while (len > 1) {
            int i = 0;
            for (; i < len - 1; i += 2) {
                ListNode node1 = lists.get(0);
                ListNode node2 = lists.get(1);
                lists.remove(node1);
                lists.remove(node2);
                lists.add(Merge(node1, node2));
            }
            if (i < len)
                len = len / 2 + 1;
            else
                len = len / 2;
        }
        return lists.get(0);
    }

    private ListNode Merge(ListNode list1, ListNode list2) {
        if (list1 == null || list2 == null)
            return list1 == null ? list2 : list1;
        ListNode dummy = new ListNode(-1);
        ListNode pre = dummy;
        while (list1 != null && list2 != null) {
            if (list1.val < list2.val) {
                pre.next = list1;
                pre = list1;
                list1 = list1.next;
            } else {
                pre.next = list2;
                pre = list2;
                list2 = list2.next;
            }
        }
        if (list1 == null)
            pre.next = list2;
        if (list2 == null)
            pre.next = list1;
        return dummy.next;
    }
}
